from selenium import webdriver
from selenium.webdriver.common.by import By

# 启动 Edge 浏览器
driver = webdriver.Edge()
print("Edge 浏览器已启动。")

# 打开页面
driver.get("file:///F:/TestProject/register.html")
print(f"页面已打开：{driver.current_url}")

# 获取当前窗口句柄
current_handle = driver.current_window_handle
print(f"获取当前窗口句柄：{current_handle}")

# 点击链接打开新窗口
try:
    driver.find_element(By.ID, "fw").click()
    print("点击链接，尝试打开新窗口。")
except Exception as e:
    print(f"点击链接时出错：{e}")

# 获取所有窗口句柄
all_handles = driver.window_handles
print(f"获取所有窗口句柄：{all_handles}")

# 切换到新窗口
new_handle = None
for handle in all_handles:
    if handle != current_handle:
        new_handle = handle
        break

if new_handle:
    driver.switch_to.window(new_handle)
    print(f"切换到新窗口：{new_handle}")
else:
    print("未找到新窗口句柄。")

# 截图
driver.save_screenshot("new_window.png")
print("截图已保存为 'new_window.png'。")

# 切换回原窗口
driver.switch_to.window(current_handle)
print(f"切换回原窗口：{current_handle}")

# 关闭浏览器
driver.quit()
print("浏览器已关闭。")